package db_migrater

import (
	"fmt"
	"goravel/app/models"
	"slices"
	"strconv"
	"strings"

	"github.com/goravel/framework/contracts/console"
	"github.com/goravel/framework/contracts/console/command"
	"github.com/goravel/framework/facades"
)

type MigrationTask struct {
}

// Signature The name and signature of the console command.
func (receiver *MigrationTask) Signature() string {
	return "db-migrate:migration_task"
}

// Description The console command description.
func (receiver *MigrationTask) Description() string {
	return "迁移任务，注意：选项要在参数前定义"
}

// Extend The console command extend.
func (receiver *MigrationTask) Extend() command.Extend {
	return command.Extend{
		Category: "db-migrater",
		Flags: []command.Flag{
			&command.StringFlag{
				Name: "name",
				Aliases: []string{"n"},
				Value: "",
				Usage: "migration task name",
			},
			&command.StringFlag{
				Name: "remark",
				Aliases: []string{"r"},
				Value: "",
				Usage: "migration task remark",
			},
		},
	}
}

// Handle Execute the console command.
func (receiver *MigrationTask) Handle(ctx console.Context) error {
	action := ctx.Argument(0);

    if ! slices.Contains(actions, action) {
        ctx.Warning("不支持的操作【" + action + "】，允许操作：" + strings.Join(actions, "、"))
        return nil
    }

    if action == "create" {
        receiver.actionCreate(ctx)
    } else if action == "all" {
        receiver.actionAll(ctx)
    }
    // todo ↑↑↑ 修改成动态调用方法 ↑↑↑
    // method := reflect.ValueOf(receiver).MethodByName(action)
    // method.Call(ctx)

    return nil
	
	return nil
}

func (receiver *MigrationTask) actionCreate(ctx console.Context) error {
    // example: ./artisan db-migrate:migration_task --name=testtask --remark="test task remark" create
    ctx.Info("开始创建迁移任务")

	// model
	migrationTask := models.MigrationTask{
		Name: ctx.Option("name"),
		Remark: ctx.Option("remark"),
	}
	err := facades.Orm().Query().Create(&migrationTask)
    if err != nil {
        ctx.Error("创建失败：" + err.Error())
        return nil
    }

    ctx.Success("迁移任务创建成功，ID：" + strconv.Itoa(int(migrationTask.ID)))
    return nil
}

func (receiver *MigrationTask) actionAll(ctx console.Context) error {
	ctx.Info("查询全部原数据库信息")

    var migrationTasks []models.MigrationTask
    facades.Orm().Query().Find(&migrationTasks)

    separator := "***************"
    for i, migrationTask := range migrationTasks {
        ctx.Line(separator + " row " + strconv.Itoa(i + 1) + ". " + separator)

        // migrationTaskType := reflect.TypeOf(migrationTask)
        // migrationTaskValue := reflect.ValueOf(migrationTask)
        // for i := range migrationTaskType.NumField() {
        //     migrationTaskValue.Field(i).Interface()
        //     ctx.Line(fmt.Sprintf("%20s", migrationTaskType.Field(i).Name) + " : ")
        // }
        // todo ↑↑↑ 这里需要修改自动遍历字段，使用reflect方式会额外遍历Model、Timestamps。

        ctx.Line(fmt.Sprintf("%20s", "id : ") + strconv.Itoa(int(migrationTask.ID)))
        ctx.Line(fmt.Sprintf("%20s", "name : ") + migrationTask.Name)
        ctx.Line(fmt.Sprintf("%20s", "remark : ") + migrationTask.Remark)
        ctx.Line(fmt.Sprintf("%20s", "created_at : ") + migrationTask.CreatedAt.Format("2006-01-02 15:04:05"))
        ctx.Line(fmt.Sprintf("%20s", "updated_at : ") + migrationTask.UpdatedAt.Format("2006-01-02 15:04:05"))
        // todo ↑↑↑ timestamp.Format格式化错误 ↑↑↑
    }

    ctx.NewLine(1)
    ctx.Line("Total lines: " + strconv.Itoa(len(migrationTasks)))

    // ctx.TwoColumnDetail("Total Size", fmt.Sprintf("%.3f MB", 110))

    return nil
}